﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YTSK.Model;
using System.Windows.Forms;

namespace YTSK.cSK.BW
{
    class Swith
    {
        public static string proc(FpType cbilltype,   Model.SK_SalebillVouch sk,
            List<Model.SK_SalebillVouchs_View> l_sks, out string fpdm, out string fphm)
        {
            var err = "";
            var maxmoney =cSKSet.GetMaxMoney(cbilltype);
            var fpmoney = l_sks.Sum(s => s.iSumSale.ObjToDecimal());
            if (fpmoney > maxmoney)
            {
                err = string.Format("[{0}]发票金额[{1}]大于税控机最大开票限额[{2}]", cbilltype, fpmoney, maxmoney);
                fpdm = ""; fphm = ""; return err;
            }
            bool bret = CheckKPCount(l_sks);
            if (!bret)
            {
                err = string.Format("系统传递税控的金额可能回产生1分钱的误差，请注意手工调整正确");
                MessageBox.Show(err,"警告", MessageBoxButtons.OK, MessageBoxIcon.Information );
            }

            string filename;
            switch (cbilltype)
            {
                case FpType.纸质专用发票:
                    err+=cMakeXML_ZP.MakeXML(sk, l_sks, out filename);
                    err+= cKP_ZP.proc(filename, out fpdm, out fphm);
                    break;
                case FpType.纸质普通发票:
                    err += cMakeXML_ZP.MakeXML(sk, l_sks, out filename);
                    err += cKP_PP.proc(filename,out fpdm, out fphm);
                    break;
                default:
                    fpdm = "";fphm = "";
                    err = "暂不支持";
                    break;
            }
            return err;
        }

        #region 检查开票系统是否会有1分钱的误差
        /// <summary>
        /// 检查开票系统是否会有1分钱的误差
        /// </summary>
        /// <param name="l_rds"></param>
        /// <returns></returns>
        public static bool CheckKPCount(List<Model.SK_SalebillVouchs_View> l_sks)
        {
            var bret = true;
            for (int i = 0; i < l_sks.Count; i++)
            {
                var t = l_sks[i];
                var isum = t.iSumSale.ObjToDecimal();
                var iMoney = Math.Round(isum / (decimal)1.17, 2);
                var itax = Math.Round(iMoney * (decimal)0.17, 2);
                if((iMoney+itax)!=isum)
                {
                    bret = false;
                }
            }
            return bret;        
        }
        #endregion

    }
}
